﻿using System;
using System.Collections.Generic;

public class ObjectPool<T>
{
    /// <summary>
    /// 当对象池中的对象不够时，用这个来创建新对象，类似于C++中指向函数的指针
    /// </summary>
    /// <returns>新对象</returns>
    public delegate T CreateNewObject();
    public CreateNewObject NewObjectCreator { get; set; }

    Queue<T> pool;

    public ObjectPool(CreateNewObject creator, int size = 10)
    {
        NewObjectCreator = creator;
        pool = new Queue<T>(size);
    }

    public T GetObject()
    {
        T data;
        if (pool.Count > 0)
            data = pool.Dequeue();
        else
            data = NewObjectCreator();
        return data;
    }
    /// <summary>
    /// 回收对象
    /// </summary>
    public void RecircleObject(T obj)
    {
        pool.Enqueue(obj);
    }
}

